/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.WADTools;

public class ReceiveAutoDocumentInfo extends HttpServlet {
  private static final long serialVersionUID = 2958522194838410612L;

  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;

  private String serverName = "localhost";
  public Properties prop = new Properties();
  private HttpSession session;
  private int lenght_transaction_ID = 6; //define lenght string of transactionID
  private String file_transaction_ID;
  private Properties data_properties = new Properties();
  private String owner_Name;
  private String app_Path;

  /**Initialize global variables*/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    session = request.getSession(false);
    //PrintWriter out = response.getWriter();
    app_Path = WADTools.APP_PATH;
    file_transaction_ID = app_Path+"res/transaction_ID.tid" ;
    owner_Name = (String)session.getAttribute("UserName");

    prop.load(new FileInputStream(app_Path+"res/wad_app.properties"));

    //set Properties from other datas
    Enumeration paramNames = request.getParameterNames();
    while(paramNames.hasMoreElements()) {
      String paramName = paramNames.nextElement().toString();
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0){
          this.data_properties.setProperty(paramName,"    -");
        }else{
          this.data_properties.setProperty(paramName,paramValue);
        }
      }else{
        for(int i=0; i<paramValues.length; i++) {
          this.data_properties.setProperty(paramName,paramValues[i]);
        }
      }
    }

    //get template ID from this form and find who is the first powered user name
    //and save it in that path

    String template_ID = request.getParameter("template_ID");
    //load object docTemplate.info to find first powered user name
    try{
      //find the first powered User from method getFirstUser from class DocumentTemplateInfo
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/activeDocTemplate/" + template_ID + "/docTemplate.info"));
      DocumentTemplateInfo dti  = (DocumentTemplateInfo)ois.readObject();
      String first_powered_User_Name = dti.getFirstUser();
      ois.close();
      
      //save object in file transactionID.info in path of the first powered User
      String uniqueTID =  get_uniqueTransactionID();
      File ipad_dir = new File(app_Path+"res/docs/InProgressAutoDoc/");
      if(!ipad_dir.exists())
        ipad_dir.mkdir();
      File dir = new File(app_Path+"res/docs/InProgressAutoDoc/" + first_powered_User_Name);
      if(!dir.exists())
        dir.mkdir();
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(app_Path+"res/docs/InProgressAutoDoc/"+first_powered_User_Name+"/"+"trans_"+uniqueTID+".info"));
      AutoDocumentTransaction adt = new AutoDocumentTransaction(uniqueTID, data_properties, owner_Name);
      oos.writeObject(adt);
      oos.close();

      response.sendRedirect("/WADSWeb/start_flow.html");
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
  
  /**Clean up resources*/
  public void destroy() {
  }


  public static String int2ConstLenString(String input, int len){
    if(len < input.length()){
      return input.substring(0, len - 1);
    }
    
    char[] cprefix = new char[len - input.length()];
    
    for(int i = 0; i < cprefix.length; i++)
      cprefix[i] = '0';
    
    return (new String(cprefix) + input);
   }

   public String get_uniqueTransactionID(){
     //add code here to find the unique ID for the transaction
     //this part you can discuss with A_KIJI.. he has some experience about this

     /*first way to make transaction ID : load file transaction_ID.tid from database before
       and get the last transaction after that the new transation ID = last transaction id +1
       and return it
     */

    int trans_ID = -1;//no transaction id before
    String transaction_ID;

    try{
      FileReader fr = new  FileReader(file_transaction_ID);
      BufferedReader b = new BufferedReader(fr);
      trans_ID = Integer.parseInt(b.readLine());
      fr.close();
    }catch(Exception e){ e.printStackTrace(); }

    if(trans_ID != -1){
       transaction_ID = int2ConstLenString(String.valueOf(trans_ID + 1), lenght_transaction_ID);
    }else{
      transaction_ID = "000000";
    }

    try{
      FileWriter fw = new  FileWriter(file_transaction_ID);
      fw.write(transaction_ID);
      fw.close();
    }catch(Exception e){ System.out.println(e); }

    return transaction_ID;
  }
}